package cn.lyq.card.ui.bank

import android.view.View
import androidx.lifecycle.Observer
import cn.lyq.card.R
import cn.lyq.card.base.BaseActivity
import cn.lyq.card.data.model.BankCardInfo
import cn.lyq.card.data.src.Status
import cn.lyq.card.global.BusTag
import cn.lyq.card.manager.UserManager
import cn.lyq.card.utils.getVisibility
import cn.lyq.card.utils.loadUrl
import cn.lyq.card.utils.setClick
import cn.lyq.card.utils.toBankNo
import com.blankj.utilcode.util.BusUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.act_bank_card.*
import kotlinx.android.synthetic.main.layout_title.*


class BankCardActivity : BaseActivity() {

    private val mModel by lazy {
        getVM(BankVM::class.java)
    }

    override fun getLayoutId(): Int {
        return R.layout.act_bank_card
    }

    override fun initView() {
        super.initView()
        setMyTitle(R.string.str_bank_card)
        tvTitleSplit.visibility = View.GONE
    }

    override fun initListener() {
        super.initListener()
        imgBg.setClick {
            BankCardAddActivity.start(this)
        }
        tvChangeBankCard.setClick {
            BankCardAddActivity.start(this)
        }
    }

    override fun initObserver() {
        super.initObserver()
        val bankCardInfo = UserManager.bankCardInfo
        if (bankCardInfo == null) {
            getData()
        }else{
            setData(bankCardInfo)
        }
    }

    private fun getData() {
        mModel.getBankCardInfo().observe(this, Observer {
            when (it?.status) {
                Status.LOADING -> showLoading()
                Status.SUCCESS -> {
                    val cardInfo = it.requireData()
                    UserManager.bankCardInfo = cardInfo
                    setData(cardInfo)
                    dismissLoading()
                }
                Status.ERROR -> {
                    ToastUtils.showShort(it.message.getMsg())
                    dismissLoading()
                }
            }
        })
    }

    private fun setData(info: BankCardInfo?) {
        groupBankCard.visibility = getVisibility(info == null)
        tvChangeBankCard.visibility = getVisibility(info == null)
        imgBg.setImageResource(if (info == null) R.drawable.ic_add_bank_card else R.drawable.ic_bank_card_bg)
        info?.let {
            imgBank.loadUrl(info.image)
            tvBankName.text = info.name
            tvBankCardNo.text = info.cardNumber?.toBankNo() ?: ""
        }
    }

    @BusUtils.Bus(tag = BusTag.BANK_CARD_REFRESH)
    fun bankRefresh() {
        getData()
    }
}